package com.dylan.shot.head.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Dylan on 2017/9/5.
 */
@Component
public class GeneralAccessInterceptor extends HandlerInterceptorAdapter {
    private Logger LOG = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String url = request.getRequestURI();
        StringBuilder param = new StringBuilder();
        Map<String, String[]> requestMap = request.getParameterMap();
        for (Map.Entry<String, String[]> reqParam : request.getParameterMap().entrySet()) {
            String key = reqParam.getKey();
            for (String value : requestMap.get(key)) {
                param.append(key).append("=").append(value).append("&");
            }
        }
        if (param.length() != 0 && param.charAt(param.length() - 1) == '&') {
            param.deleteCharAt(param.length() - 1);
        }
        Cookie[] cookies = request.getCookies();
        Map<String, String> cookieMap = new HashMap<>();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie.getValue());
            }
        }
        //显示请求参数
        LOG.info("Access Report [{}] ------ clientIP: {} || request: {} || params: {} || cookies: {}", request.getMethod(), getRemoteHost(request), url, param, cookieMap.toString());
        return true;
    }

    private static String getRemoteHost(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }

}
